package es.esi.gemde.methodmanager.service.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWizard;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.wizards.IWizardDescriptor;

import es.esi.gemde.methodmanager.CommandConstants;

public class CallWizardCommandHandler extends AbstractHandler {
	
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		String wizard = event.getParameter(CommandConstants.WIZARD_PARAM_ID);
		
		if (wizard != null) {
			IWizardDescriptor wizDescriptor;
			
			// Try to load the wizard as an extension to Eclipse
			wizDescriptor = PlatformUI.getWorkbench().getExportWizardRegistry().findWizard(wizard);
			if (wizDescriptor == null) {
				wizDescriptor = PlatformUI.getWorkbench().getImportWizardRegistry().findWizard(wizard);
			}
			if (wizDescriptor == null) {
				wizDescriptor = PlatformUI.getWorkbench().getNewWizardRegistry().findWizard(wizard);
			}
			
			if (wizDescriptor != null) {
				try {
					IWorkbenchWizard wiz = wizDescriptor.createWizard();
					wiz.init(PlatformUI.getWorkbench(), StructuredSelection.EMPTY);
					WizardDialog dialog = new WizardDialog(new Shell(), wiz);
					dialog.open();
				} catch (CoreException e) {
					throw new ExecutionException("Exception raised creating the wizard", e);
				}
			}
			else {
				// Try to load the wizard parameter as a class
				try {
					Class<?> c = Class.forName(wizard);
					Object obj = c.newInstance();
					
					if (obj instanceof IWizard) {
						IWizard wiz = (IWizard) obj;
						WizardDialog dialog = new WizardDialog(new Shell(), wiz);
						dialog.open();
					}
					else {
						throw new ExecutionException("The provided class is not an instance of IWizard");
					}
				}
				catch (ClassNotFoundException e) {
					throw new ExecutionException("Cannot find the provided wizard", e);
				} catch (InstantiationException e) {
					throw new ExecutionException("Cannot instantiate the provided wizard class", e);
				} catch (IllegalAccessException e) {
					throw new ExecutionException("Cannot access the provided wizard class", e);
				}
			}
		}
		else {
			throw new ExecutionException("Wizard parameter was not provided. Cannot call the wizard.");
		}
		
		return null;
	}

}